/*
 * Copyright (c) 2011-2012 Alexander Dubu
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * o  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * o  Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * o  Neither the name Axil nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package axil.stdlib.collection.type;

import axil.api.AxilObject;
import axil.api.AxilType;
import axil.etc.Cloned;
import axil.etc.ConditionallyImmutable;
import axil.framework.collection.SafeIterator;
import axil.framework.type.Added;
import axil.framework.type.Subtracted;
import axil.stdlib.core.type.Nil;
import axil.stdlib.numbers.type.Int;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import static axil.framework.Functions.*;


/**
 * An Axil implementation of an array or arbitrary Axil object, where the array
 * automatically resizes to accommodate the values.
 */
public class Arry<T extends AxilObject> extends AxilCollection<T>
	implements Sequence<T>, ConditionallyImmutable<Arry<T>>,
	Cloned<Arry<T>>, Added, Subtracted, Keyed {
	public static final AxilType type = Arry_Type.object;
	public static final Arry empty = (Arry)(new Arry().immute());

	private ArrayList<T> list;
	private boolean immutable;

    // Empty constructor for reflection
    public Arry() {
        list = new ArrayList<T>(0);
    }
    
	/**
	 * Create a new array of values.
	 *
	 * @param values
	 * 	The array of values. Since the passed value comes from an array that
	 * 	could have side effects, we make a new array to contain the values.
	 */
	public Arry(T... values) {
		final int size = values.length;
		list = new ArrayList<T>(size);
		for (T v : values) {
			list.add(v);
		}
	}


	/**
	 * Create a new array of values.
	 *
	 * @param collection
	 * 	The collection of values.
	 */
	public Arry(AxilCollection<T> collection) {
		final int size = collection.size();
		list = new ArrayList<T>(size);
		for (T v : collection) {
			list.add(v);
		}
	}


	/**
	 * Create a new array of values.
	 *
	 * @param collection
	 * 	The collection of values. Since the passed value comes from a collection
	 * 	that could have side effects, we make a new array to contain the values.
	 */
	public Arry(Collection<T> collection) {
		final int size = collection.size();
		list = new ArrayList<T>(size);
		for (T v : collection) {
			list.add(v);
		}
	}


	public Arry(int size) {
		list = new ArrayList<T>(size);
	}


	private Arry(Arry<T> other) {
		this.list = (ArrayList<T>)other.list.clone();
		this.immutable = false;
	}


	/**
	 * Get the type metadata for this object. The type metadata contains
	 * information about the type itself, as an object.
	 */
	public AxilType type() {
		return type;
	}


	/**
	 * Tell if this collection contains the value (not the key) given.
	 */
	public boolean has(AxilObject object) {
		return list.contains(object);
	}


	/**
	 * Tell if this object is equivalent to the given object. The object given
	 * is never null. The object given may be of any type of value object.  If
	 * the given object is not a suitable type for comparison, a
	 * ClassCastException may be thrown.
	 */
	public boolean equalTo(AxilObject object) {
		if (object instanceof AxilCollection) {
			return sameAs((AxilCollection)object);
		}
		return false;
	}


	/**
	 * Compares this object with the specified object for order. If the given
	 * object is not a suitable type for comparison, an error may
	 * be thrown.
	 *
	 * @param object
	 * 	The object to compare against. The given object cannot be null but may
	 * 	be any Axil object.
	 *
	 * @return
	 * 	Returns a negative integer, zero, or a positive integer as this object
	 * 	is less than, equal to, or greater than the specified object.
	 */
    @Override
	public int comparedTo(AxilObject object) {
        if (object instanceof Arry) {
            return compareContents((Arry)object);
        }
        // If not an array, use the default comparison
        return super.comparedTo(object);
    }


    /**
     * @see AxilObject#exactly(axil.api.AxilObject)
     */
    @Override
    public boolean exactly(AxilObject object)
    {
        if (object.type() == this.type()) {
            // Both must be Arrys, and have the same objects, in the same order.
            return (0 == comparedTo((Arry)object));
        }
        return false;
    }


    /**
     * Compares the contents of this object with the contents of the specified object
     * for order.  Returns a negative integer, zero, or a positive integer as
     * this object is less than, equal to, or greater than the specified object.
     */
    public int compareContents(Arry objects) {
        // compare the objects in each array, in order.
        int lowestSize = this.size();
        if (lowestSize > objects.size()) {
            lowestSize = objects.size();
        }
        // Compare the contents (for as many as overlap in size).
        for (int nextIndex = 0; nextIndex < lowestSize; nextIndex++) {
            AxilObject thisObject = this.at(nextIndex);
            AxilObject otherObject = objects.at(nextIndex);
            int compareResult = thisObject.comparedTo(otherObject);
            if (compareResult != 0) {
                return compareResult;
            }
        }
        // The arrays were equal for as many items as we were able to compare; comes down to size.
        return this.size() - objects.size();
    }


    /**
	 * Get the first element from this sequential collection, or return null
	 * if this collection is empty.
	 */
	public T first() {
		return empty() ? null : (T)list.get(0);
	}


	/**
	 * Get the last element from this sequential collection, or return null if
	 * this collection is empty.
	 */
	public T last() {
		return empty() ? null : list.get(size() - 1);
	}


	/**
	 * Return the key where the given object resides within this collection.
	 * A nil value is returned if the object does not live in this collection.
	 */
	public AxilObject keyof(AxilObject object) {
		int i = list.indexOf(object);
		return i < 0 ? Nil.object : Int.from(i + 1);
	}


	/**
	 * Return the object at the given key, or nil if the key is not contained
	 * within this object.
	 */
	public AxilObject at(AxilObject key) {
		if (key == Nil.object) {
			return key;
		}
		int i = cast(Int.class, key).value() - 1;
		if ((i >= 0) && (i < size())) {
			return list.get(i);
		}
		return Nil.object;
	}


	/**
	 * Get the element at the given index, where the first object is at index
	 * zero. If there is no element at that position, then a null is returned.
	 */
	public T at(int index) {
		if ((index < 0) || (index >= list.size())) {
			return null;
		}
		return list.get(index);
	}


	public Arry<T> put(T value) {
        // The genericizing to "T" is being confused when passed an AxilCollection.
        if (value instanceof AxilCollection) {
            return this.put((AxilCollection)value);
        }
        edit();
		list.add(value);
		return this;
	}


	public Arry<T> put(T... values) {
		edit();
		for (T v : values) {
			list.add(v);
		}
		return this;
	}


	public Arry<T> put(AxilCollection<T> values) {
		edit();
		for (T v : values) {
			list.add(v);
		}
		return this;
	}


	public Arry<T> at(int index, T value) {
		edit();
		final int actual = list.size();
		if (index >= actual) {
			for (int i = actual; i < index; i ++) {
				list.add((T)Nil.object);
			}
			list.add(value);
		} else {
			list.set(index, value);
		}
		return this;
	}


	/**
	 * Add the given value to this value, returning a new object. The given
	 * value is never null or nil. The value may be a numeric type of any other
	 * type of object that can sensibly implement the Added interface.
	 */
	public AxilObject add(AxilObject object) {
        if (object == Nil.object) {
            return Nil.object;
        }
        if (immutable) {
			return cloned().put((T)object).immute();
		}
		return put((T)object).immute();
	}


	/**
	 * Subtract the given object from this object. The given value is never
	 * null or nil. The value may be a numeric type of any other type of object
	 * that can sensibly implement the Subtracted interface.
	 */
	public AxilObject subtract(AxilObject n) {
        if (n == Nil.object) {
            return Nil.object;
        }
        Arry obj = immutable ? cloned() : this;
		Iterator<AxilObject> i = obj.list.iterator();
		if (n instanceof AxilCollection) {
			AxilCollection c = (AxilCollection)n;
			while(i.hasNext()) {
				if (c.has(i.next())) {
					i.remove();
				}
			}
		} else {
			while(i.hasNext()) {
				if (i.next().equals(n)) {
					i.remove();
				}
			}
		}
		return obj.immute();
	}


	/**
	 * Return a subset of this object. The begin and end are zero-based indexes.
	 * The end may be -1, indicating the natural end of the list. The begin/end
	 * values are automatically adjusted to be within bounds.
	 */
	public Arry<T> slice(int begin, int end) {
		final int size = size();
		if (begin >= size) {
			return empty;
		}
		if ((end < 0) || (end >= size)) {
			end = size - 1;
		}
		Arry a = new Arry(end - begin + 1);
		for (int i = begin; i <= end; i++) {
			a.put(at(i));
		}
		return a.immute();
	}


	/**
	 * Clone this object, returning a new object. The clone is sufficiently
	 * deep to ensure that any modifications to the clone, or to any member of
	 * the clone, do not impact this object.
	 */
	public Arry<T> cloned() {
		return new Arry<T>(this);
	}


	/**
	 * Mark this object as immutable, preventing any further changes. Any
	 * attempt to alter this collection after this point results in an exception.
	 */
	public Arry<T> immute() {
		this.immutable = true;
		return this;
	}


	private void edit() {
		if (immutable) {
            throw error(axil(), "immutable-object");
		}
	}


	/**
	 * Get the size of this collection.
	 */
	public int size() {
		return list.size();
	}


	/**
	 * Returns an iterator over a set of elements of type T. The iterator
	 * returned does not allow for alteration of this collection.
	 */
	public Iterator<T> iterator() {
		return new SafeIterator<T>(list);
	}
}
